/**
 * 定义全局axios拦截器
 */
import axios from "axios";
import router from "./router";
import Element from "element-ui"

// 后台接口
axios.defaults.baseURL = "http://127.0.0.1:8888";

const request = axios.create({
    timeout: 5000,
    headers: {
        'Content-Type': "application/json; charset=utf-8"
    }
});

/**
 * 请求拦截
 */
request.interceptors.request.use(config => {
    config.headers['Authorization'] = localStorage.getItem("token");
    return config;
});

/**
 * 响应拦截
 */
request.interceptors.response.use(
    response => {
        let res = response.data;
        if (res.code === 200) {
            return response
        } else {
            Element.Message.error(!res.message ? '系统异常' : res.message);
            return Promise.reject(response.data.message)
        }
    },
    error => {
        if (error.response.data) {
            error.massage = error.response.data.message;
        }
        if (error.response.status === 401) {
            router.push("/login")
        }
        Element.Message.error(error.massage, {duration: 3000});
        return Promise.reject(error)
    }
);

export default request
